from datetime import datetime
from django.db import transaction
from django.db.models import F

from server.apps.blogs.logic.posts.types import (
    BlogPostId,
    ValidPostData,
    ValidScore,
)
from server.apps.blogs.models import BlogPost
from server.apps.blogs.logic.posts import queries as post_queries


def create(valid_data: ValidPostData) -> BlogPost:
    """
    Creates a new blog post.

    Note: you cannot create a BlogPost from **invalid** data!
    mypy will catch that.
    """
    new_slug = valid_data.title.replace(' ', '-')
    valid_slug = post_queries.sluged(new_slug)
    slug_date = datetime.now.strftime("%Y-%m-%d-%H%M%S")
    print(slug_date)
    if bool(valid_slug):
        new_slug += '-' + slug_date
    with transaction.atomic():
        new_post = BlogPost.objects.create(
            title=valid_data.title,
            body=valid_data.body,
            author=valid_data.author,
            slug=new_slug
        )
        return new_post


def update_post(valid_data: ValidPostData, slug: str) -> BlogPost:
    """Updates post score."""
    with transaction.atomic():
        post = BlogPost.objects.select_for_update().get(slug=slug)
        post.title = valid_data.title
        post.body = valid_data.body
        post.author = valid_data.author
        post.save(update_fields=['title', 'body', 'author'])
    return post
